﻿namespace EFS.RC.CommunicatorContext.Operators
{
    public partial class Main : EFS.RC.CommunicatorContext.Common.Pages.Page
    {
        #region Locals
        /// sycn access for lync events
        private System.Object syncAccessLyncEvents = new System.Object();

        /// sycn access for keep alive
        private System.Object syncAccessLyncUpdate = new System.Object();
       // private System.Windows.Threading.DispatcherTimer dispatcherTimerLyncUpdate = null;
        #endregion

        #region Constructors
        /// Implicit
        public Main()
        {
            // init component
            InitializeComponent();

            // set operator type
            OperatorType = EFS.RC.CommunicatorContext.Common.Functions.OperatorType.NotSet;

            // ignore in design tool
            if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
            {
                // conversation classification
                controlAgentControls.controlCoversationClassification.SelectionChanged += ConversationClassification_SelectionChanged;
                controlAgentControls.controlQuestionnaire.SelectionChanged += Questionnaire_SelectionChanged;
                controlSupervisorControls.controlCustomerSurvey.SelectionChanged += CustomerSurvey_SelectionChanged;
                controlAgentControls.controlHuntGroupInvite.SelectionChanged += HuntGroupInvite_SelectionChanged;
                // search
                controlSearch.OpenParty += Search_Open;

                // get conversation
                try
                {
                    TRACE_INTERNAL("Main:ctor Lync Conversation: GET HOSTED");
                    LyncConversation = (Microsoft.Lync.Model.Conversation.Conversation)Microsoft.Lync.Model.LyncClient.GetHostingConversation();

                    // if we run it local
                    if (null != LyncConversation)
                    {
                        TRACE_INTERNAL("Main:ctor Lync Conversation: FOUND");

                        // To handle context data the application needs to register for these two events.
                        LyncConversation.InitialContextReceived += new System.EventHandler<Microsoft.Lync.Model.Conversation.InitialContextEventArgs>(LyncConversation_InitialContextReceived);
                        LyncConversation.ContextDataReceived += new System.EventHandler<Microsoft.Lync.Model.Conversation.ContextEventArgs>(LyncConversation_ContextDataReceived);

                        // start keep alive
                        //StartLyncConnectionUpdate();

                        // handle application data in case this was slow loading
                        HandleApplicationData(LyncConversation.GetApplicationData(LyncApplicationId));

                        // do not close on idle
                        LyncConversation.BeginSetProperty(Microsoft.Lync.Model.Conversation.ConversationProperty.AutoTerminateOnIdle, false, EndSetProperty, null);

                        TRACE_INTERNAL("Main:ctor Lync Conversation: INITIALIZED");
                    }
                    else
                    {
                        TRACE_INTERNAL("Main:ctor Lync Conversation:: NOT FOUND");
                    }
                }
                catch (System.Exception ex)
                {
                    TRACE_INTERNAL(ex);

                    // show error
                    ShowErrorMessage("Failed to initialize lync conversation.", ex);

                    // throw
                    throw ex;
                }
            }

            ////////// Init handlers
            // controls
            controlSupervisorControls.Button_Clicked += new System.EventHandler<EFS.RC.CommunicatorContext.Operators.Controls.ButtonsEventArgs>(controlSupervisorControls_Button_Clicked);
            controlSupervisorControls.RequestCustomerSurvey += new System.EventHandler<EFS.RC.CommunicatorContext.Operators.CustomerSurvey.RequestCustomerSurveyArgs>(controlSupervisorControls_ButtonRequestCustomerSurvey_Clicked);
            controlAgentControls.Button_Clicked += new System.EventHandler<EFS.RC.CommunicatorContext.Operators.Controls.ButtonsEventArgs>(controlAgentControls_Button_Clicked);

            tabTRACE_INTERNAL.Visibility =
                EFS.RC.CommunicatorContext.Common.Config.Main.Tracing ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }
        #endregion

        #region UI
        // Set controls tab for Agents or Supervisors
        private void SetControlsTab()
        {
            //operator is Agent
            if (OperatorType == EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Agent)
            {
                tabSupervisorControls.Visibility = System.Windows.Visibility.Collapsed;
                tabAgentControls.IsSelected = true;
            }
            //operator is Supervisor
            else if (OperatorType == EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Supervisor)
            {
                tabAgentControls.Visibility = System.Windows.Visibility.Collapsed;
                tabSupervisorControls.IsSelected = true;
            }
        }
        #endregion

        #region Properties
        /// Property CustomerTelephone: Get, Set
        private System.String CustomerTelephone { get; set; }

        /// Property LyncConversation: Get, Set
        private Microsoft.Lync.Model.Conversation.Conversation LyncConversation { get; set; }

        /// Property LyncApplicationId: Get, Set
        private System.String LyncApplicationId
        {
            get
            {
                return "{2B1F4C61-F39A-1E4C-95F4-115F76AD35AA}";
            }
        }

        /// Property OperatorType: Get, Set
        private EFS.RC.CommunicatorContext.Common.Functions.OperatorType OperatorType { get; set; }
        #endregion

        #region Lync Events
        /// <summary>
        /// Initial context received event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void LyncConversation_InitialContextReceived(object sender, Microsoft.Lync.Model.Conversation.InitialContextEventArgs args)
        {
            // handle data
            HandleApplicationData(args.ApplicationData);
        }

        /// <summary>
        /// Context data received
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void LyncConversation_ContextDataReceived(object sender, Microsoft.Lync.Model.Conversation.ContextEventArgs args)
        {
            // verify context type
            if (!EFS.Common.Verify.String(args.ContextDataType))
            {
                return;
            }

            // check content type
            if (EFS.RC.CC.Messages.Message.ContentType == args.ContextDataType)
            {
                TRACE_INTERNAL(System.String.Format("Main:LyncConversation_ContextDataReceived {0}", args.ContextData));

                // get message
                EFS.RC.CC.Messages.Message message = EFS.RC.CC.Messages.Message.Deserialize(args.ContextData);

                // call message received
                HandleContextData(sender, new EFS.RC.CommunicatorContext.Common.MessageContextArgs(args));
            }
        }

        /// <summary>
        /// End set property
        /// </summary>
        /// <param name="ar"></param>
        private void EndSetProperty(System.IAsyncResult ar)
        {
            try
            {
                // check
                LyncConversation.EndSetProperty(ar);
            }
            catch (System.Exception ex)
            {
                // log the problem
                TRACE_INTERNAL(ex);
            }
        }

        /// <summary>
        /// context data sent succesfully event
        /// </summary>
        /// <param name="ar"></param>
        private void OnSendContextDataMessageCompleted(System.IAsyncResult ar)
        {
            try
            {
                // check
                LyncConversation.EndSendContextData(ar);
            }
            catch (System.Exception ex)
            {
                // log the problem
                TRACE_INTERNAL(ex);
            }
        }

        /// <summary>
        /// context data sent succesfully event
        /// </summary>
        /// <param name="ar"></param>
        private void Classification_OnSendContextDataMessageCompleted(System.IAsyncResult ar)
        {
            try
            {
                // check
                LyncConversation.EndSendContextData(ar);

                // close hosting conversation
                EFS.RC.CommunicatorContext.Common.ConversationWnd.Close(LyncConversation);
            }
            catch (System.Exception ex)
            {
                // log the problem
                TRACE_INTERNAL(ex);
            }
        }

        /// <summary>
        /// context data sent succesfully event
        /// </summary>
        /// <param name="ar"></param>
        private void Questionnaire_OnSendContextDataMessageCompleted(System.IAsyncResult ar)
        {
            try
            {
                // check
                LyncConversation.EndSendContextData(ar);

                // set to read only
                controlAgentControls.controlQuestionnaire.ReadOnly = true;
            }
            catch (System.Exception ex)
            {
                // log the problem
                TRACE_INTERNAL(ex);
            }
        }

        #region CustomFct
        /// <summary>
        /// Handle application data from context (initial or after slow loading)
        /// </summary>
        /// <param name="applicationData"></param>
        private void HandleApplicationData(System.String applicationData)
        {
            // prevent overlapping messages
            lock (syncAccessLyncEvents)
            {
                TRACE_INTERNAL(System.String.Format("Main:HandleApplicationData ({0})", applicationData));

                // retrieve data
                if (0 == System.String.Compare(applicationData, "supervisor", System.StringComparison.OrdinalIgnoreCase))
                {
                    if (OperatorType != Common.Functions.OperatorType.Supervisor)
                    {
                        TRACE_INTERNAL("Main:HandleApplicationData init context as Supervisor");

                        // set operator type
                        OperatorType = EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Supervisor;
                        SetControlsTab();

                        // notify back that this was handled
                        EFS.RC.CC.Messages.Communicator.Lync.Context.Aplication applicationContext = new EFS.RC.CC.Messages.Communicator.Lync.Context.Aplication();
                        applicationContext.Context = "supervisor";

                        // send event
                        SentMessageToContext(applicationContext, OnSendContextDataMessageCompleted);
                    }
                }
                else if (0 == System.String.Compare(applicationData, "agent", System.StringComparison.OrdinalIgnoreCase))
                {
                    if (OperatorType != Common.Functions.OperatorType.Agent)
                    {
                        TRACE_INTERNAL("Main:HandleApplicationData init context as Agent");

                        // set operator type
                        OperatorType = EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Agent;
                        SetControlsTab();

                        // notify back that this was handled
                        EFS.RC.CC.Messages.Communicator.Lync.Context.Aplication applicationContext = new EFS.RC.CC.Messages.Communicator.Lync.Context.Aplication();
                        applicationContext.Context = "agent";

                        // send event
                        SentMessageToContext(applicationContext, OnSendContextDataMessageCompleted);
                    }
                }
            }
        }

        /// <summary>
        /// Handle incomming context Data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void HandleContextData(object sender, EFS.RC.CommunicatorContext.Common.MessageContextArgs args)
        {
            // prevent overlapping messages
            lock (syncAccessLyncEvents)
            {
                if (args.Message is EFS.RC.CC.Messages.Customer.Caller)
                {
                    // convert message & load
                    EFS.RC.CC.Messages.Customer.Caller msg = (EFS.RC.CC.Messages.Customer.Caller)args.Message;
                    CustomerTelephone = msg.Telephone;
                    controlAgentControls.controlCoversationClassification.LoadClassifications(msg.CustomerEndPointId);
                }
                // Conversation::Info
                else if (args.Message is EFS.RC.CC.Messages.Communicator.Lync.Conversation.Info)
                {
                    // convert message & load
                    EFS.RC.CC.Messages.Communicator.Lync.Conversation.Info msg = (EFS.RC.CC.Messages.Communicator.Lync.Conversation.Info)args.Message;

                    //operator is supervisor
                    if (OperatorType == EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Supervisor)
                    {
                        controlSupervisorControls.coversationInfo.LoadConversationInfo(msg);
                        controlSupervisorControls.UpdateInfo(msg);
                    }
                    //operator is agent
                    else if (OperatorType == EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Agent)
                    {
                        controlAgentControls.coversationInfo.LoadConversationInfo(msg);
                        controlAgentControls.controlHuntGroupInvite.LoadConversationInfo(msg);
                        controlAgentControls.UpdateInfo(msg);
                    }
                }
                // Participant::StatusList
                else if (args.Message is EFS.RC.CC.Messages.Communicator.Lync.Participant.StatusList)
                {
                    // convert message & load
                    EFS.RC.CC.Messages.Communicator.Lync.Participant.StatusList statusList = (EFS.RC.CC.Messages.Communicator.Lync.Participant.StatusList)args.Message;
                    controlSupervisorControls.LoadParticipants(statusList);
                }
                else if (args.Message is EFS.RC.CC.Messages.Communicator.Lync.Conversation.WrapWarning)
                {
                    Microsoft.Lync.Model.Extensibility.Automation _automation = Microsoft.Lync.Model.LyncClient.GetAutomation();
                    _automation.GetConversationWindow(LyncConversation).FlashExtensibilityWindow(LyncApplicationId, true);
                }
                else if (args.Message is EFS.RC.CC.Messages.Supervisor.Agent.Request)
                {
                    // convert message & load
                    EFS.RC.CC.Messages.Supervisor.Agent.Request msg = (EFS.RC.CC.Messages.Supervisor.Agent.Request)args.Message;

                    // double check
                    switch (OperatorType)
                    {
                        case EFS.RC.CommunicatorContext.Common.Functions.OperatorType.Agent:
                            {
                                controlAgentControls.ShowInlineMessage(msg.RequestText, true, 2, true);
                                break;
                            }
                        default:
                            {
                                break;
                            }
                    }
                }
            }
        }

        /// <summary>
        /// Send message via context channel
        /// </summary>
        /// <param name="message"></param>
        private void SentMessageToContext(EFS.RC.CC.Messages.Message message, System.AsyncCallback conversationCallback)
        {
            // check
            EFS.Common.Verify.Reference(message, "message");

            try
            {
                // send
                LyncConversation.BeginSendContextData(
                    LyncApplicationId, EFS.RC.CC.Messages.Message.ContentType, EFS.RC.CC.Messages.Message.Serialize(message), conversationCallback, null);
            }
            catch (System.Exception ex)
            {
                TRACE_INTERNAL(ex);
            }
        }
        #endregion
        #endregion

        #region Utilities

        #region LyncUpdate
		///// Keep alive loop function
		//private void dispatcherTimerLyncUpdate_Tick(object sender, System.EventArgs e)
		//{
		//	// prevent overlapping messages
		//	lock (syncAccessLyncEvents)
		//	{
		//		// create keep alive message and send
		//		EFS.RC.CC.Messages.Communicator.Lync.Conversation.Update msgKA = new EFS.RC.CC.Messages.Communicator.Lync.Conversation.Update();
		//		SentMessageToContext(msgKA, OnSendContextDataMessageCompleted);
		//	}
		//}

		///// Start keep alive
		//private void StartLyncConnectionUpdate()
		//{
		//	lock (syncAccessLyncUpdate)
		//	{
		//		// only if stopped
		//		if (null == this.dispatcherTimerLyncUpdate || !this.dispatcherTimerLyncUpdate.IsEnabled)
		//		{
		//			// start
		//			this.dispatcherTimerLyncUpdate = new System.Windows.Threading.DispatcherTimer();
		//			this.dispatcherTimerLyncUpdate.Interval =
		//				new System.TimeSpan(
		//					0,
		//					0,
		//					0,
		//					0,
		//					EFS.RC.CommunicatorContext.Common.Functions.LyncConversationKeepAliveMillisecondsInterval);
		//			this.dispatcherTimerLyncUpdate.Tick += new System.EventHandler(dispatcherTimerLyncUpdate_Tick);
		//			this.dispatcherTimerLyncUpdate.Start();
		//		}
		//	}
		//}

		///// Stop keep alive
		//private void StopLyncConnectionUpdate()
		//{
		//	lock (syncAccessLyncUpdate)
		//	{
		//		// only if running
		//		if (null != this.dispatcherTimerLyncUpdate && dispatcherTimerLyncUpdate.IsEnabled)
		//		{
		//			this.dispatcherTimerLyncUpdate.Stop();
		//		}
		//	}
		//}
        #endregion

        #region TRACE_INTERNAL
        /// <summary>
        /// Good old trace
        /// </summary>
        /// <param name="value"></param>
        private void TRACE_INTERNAL(System.String value)
        {
            if (!EFS.RC.CommunicatorContext.Common.Config.Main.Tracing)
            {
                return;
            }

            // lock access
            lock (this.textBoxTRACE_INTERNAL)
            {
                if (EFS.Common.Verify.String(textBoxTRACE_INTERNAL.Text))
                {
                    textBoxTRACE_INTERNAL.Text += System.Environment.NewLine;
                }
                textBoxTRACE_INTERNAL.Text += System.DateTime.Now.ToString() + System.Environment.NewLine + "   " + value;
            }
        }

        /// <summary>
        /// Good old trace
        /// </summary>
        /// <param name="value"></param>
        private void TRACE_INTERNAL(System.Exception ex)
        {
            // create builder
            System.Text.StringBuilder sbEx = new System.Text.StringBuilder();
            sbEx.AppendFormat("{0}{1}{2}",
                ex.Message,
                System.Environment.NewLine,
                ex.StackTrace);

            // trace
            TRACE_INTERNAL(sbEx.ToString());
        }

        #endregion
        #endregion

        #region Control Events
        /// Called when a button was clicked from supervisor controls
        private void controlSupervisorControls_Button_Clicked(object sender, SupervisorControls.ButtonsEventArgs e)
        {
            try
            {
                // trace
                TRACE_INTERNAL("e.ButtonType = " + e.ButtonType.ToString() + "; LyncApplicationId = " + LyncApplicationId);

                switch (e.ButtonType)
                {
                    case SupervisorControls.ButtonType.Monitor:
                        {
                            // create message
                            EFS.RC.CC.Messages.Message msg = new EFS.RC.CC.Messages.Supervisor.Tools.Monitor();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case SupervisorControls.ButtonType.Whisper:
                        {
                            // create message
                            EFS.RC.CC.Messages.Message msg = new EFS.RC.CC.Messages.Supervisor.Tools.Whisper();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case SupervisorControls.ButtonType.BargeIn:
                        {
                            // create message
                            EFS.RC.CC.Messages.Message msg = new EFS.RC.CC.Messages.Supervisor.Tools.BargeIn();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case EFS.RC.CommunicatorContext.Operators.Controls.ButtonType.Hold:
                        {
                            // create message
                            EFS.RC.CC.Messages.Communicator.Lync.Conversation.Hold msg = new EFS.RC.CC.Messages.Communicator.Lync.Conversation.Hold();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case EFS.RC.CommunicatorContext.Operators.Controls.ButtonType.Resume:
                        {
                            // create message
                            EFS.RC.CC.Messages.Communicator.Lync.Conversation.Resume msg = new EFS.RC.CC.Messages.Communicator.Lync.Conversation.Resume();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// Called when a button was clicked from supervisor controls
        private void controlAgentControls_Button_Clicked(object sender, EFS.RC.CommunicatorContext.Operators.Controls.ButtonsEventArgs e)
        {
            try
            {
                // trace
                TRACE_INTERNAL("e.ButtonType = " + e.ButtonType.ToString() + "; LyncApplicationId = " + LyncApplicationId);

                switch (e.ButtonType)
                {
                    case EFS.RC.CommunicatorContext.Operators.Controls.ButtonType.Hold:
                        {
                            // create message
                            EFS.RC.CC.Messages.Communicator.Lync.Conversation.Hold msg = new EFS.RC.CC.Messages.Communicator.Lync.Conversation.Hold();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case EFS.RC.CommunicatorContext.Operators.Controls.ButtonType.Resume:
                        {
                            // create message
                            EFS.RC.CC.Messages.Communicator.Lync.Conversation.Resume msg = new EFS.RC.CC.Messages.Communicator.Lync.Conversation.Resume();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case EFS.RC.CommunicatorContext.Operators.Controls.ButtonType.RecorderPause:
                        {
                            // create message
                            EFS.RC.CC.Messages.Communicator.Lync.Recorder.Pause msg = new EFS.RC.CC.Messages.Communicator.Lync.Recorder.Pause();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    case EFS.RC.CommunicatorContext.Operators.Controls.ButtonType.RecorderResume:
                        {
                            // create message
                            EFS.RC.CC.Messages.Communicator.Lync.Recorder.Resume msg = new EFS.RC.CC.Messages.Communicator.Lync.Recorder.Resume();

                            // send event
                            SentMessageToContext(msg, OnSendContextDataMessageCompleted);

                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// ConversationClassification_SelectionChanged
        private void ConversationClassification_SelectionChanged(System.Int32 newSelection)
        {
            try
            {
                // only if something is selected
                if (0 == newSelection)
                {
                    return;
                }

                // trace
                TRACE_INTERNAL("ConversationClassification: newSelection = " + newSelection.ToString() + "; LyncApplicationId = " + LyncApplicationId);

                // create message
                EFS.RC.CC.Messages.Communicator.Lync.Context.Classification msg = new EFS.RC.CC.Messages.Communicator.Lync.Context.Classification();
                msg.ID = newSelection;

                // send event
                SentMessageToContext(msg, Classification_OnSendContextDataMessageCompleted);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// Questionnaire_SelectionChanged
        private void Questionnaire_SelectionChanged(System.String newSelectionCode)
        {
            try
            {
                // only if something is selected
                if (!EFS.Common.Verify.String(newSelectionCode))
                {
                    return;
                }

                // trace
                TRACE_INTERNAL("Survey: newSelectionCode = '" + newSelectionCode + "'; LyncApplicationId = " + LyncApplicationId);

                // create message
                EFS.RC.CC.Messages.Communicator.Lync.Context.Questionnaire msg = new EFS.RC.CC.Messages.Communicator.Lync.Context.Questionnaire();
                msg.Code = newSelectionCode;

                // send event
                SentMessageToContext(msg, Questionnaire_OnSendContextDataMessageCompleted);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// CustomerSurvey_SelectionChanged
        private void CustomerSurvey_SelectionChanged(System.Int32? newSelectionID)
        {
            try
            {
                // only if something is selected
                if (!newSelectionID.HasValue)
                {
                    return;
                }

                // trace
                TRACE_INTERNAL(System.String.Format("Survey: newSelectionID = '{0}'; LyncApplicationId = {1}", newSelectionID, LyncApplicationId));

                // set to read only
                controlSupervisorControls.controlCustomerSurvey.ReadOnly = true;

                // start survey
                EFS.RC.CommunicatorContext.Common.Functions.StartSurveyExternal(controlSupervisorControls.ConversationGuid, newSelectionID.Value);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// HuntGroupInvite_SelectionChanged
        private void HuntGroupInvite_SelectionChanged(EFS.RC.CC.Messages.Communicator.Lync.Context.HuntGroupInvite inviteMessage)
        {
            try
            {
                // only if something is selected
                if (null == inviteMessage)
                {
                    return;
                }

                // trace
                TRACE_INTERNAL("Hunt Group Invite: " + inviteMessage.ToString() + "; LyncApplicationId = " + LyncApplicationId);

                // send event
                SentMessageToContext(inviteMessage, OnSendContextDataMessageCompleted);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// CreditCardDataProtection_Closed
        private void CreditCardDataProtection_Closed()
        {
            try
            {
                // trace
                TRACE_INTERNAL("Credit Card Data Protection: Resuming Recorder; LyncApplicationId = " + LyncApplicationId);

                // send event
                SentMessageToContext(new EFS.RC.CC.Messages.Communicator.Lync.Recorder.Resume(), OnSendContextDataMessageCompleted);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// Search_Open
        private void Search_Open(EFS.CC.HW.Views.BeneficiaryInfo beneficiaryInfo)
        {
            try
            {
                // only if something is selected
                if (null == beneficiaryInfo)
                {
                    return;
                }

                // trace
                TRACE_INTERNAL(System.String.Format("Search_Open; LyncApplicationId = {0} {1} {2}",
                    LyncApplicationId,
                    null == beneficiaryInfo.ApplicantID ? 0 : beneficiaryInfo.ApplicantID.Value,
                    null == beneficiaryInfo.PartyID ? 0 : beneficiaryInfo.PartyID.Value));

                // create message
                EFS.RC.CC.Messages.Communicator.Lync.Context.HW msg = new EFS.RC.CC.Messages.Communicator.Lync.Context.HW();
                msg.ApplicantID = null == beneficiaryInfo.ApplicantID ? 0 : beneficiaryInfo.ApplicantID.Value;
                msg.PartyID = null == beneficiaryInfo.PartyID ? 0 : beneficiaryInfo.PartyID.Value;

                // send event
                SentMessageToContext(msg, OnSendContextDataMessageCompleted);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Error sending Discovery message.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }

        /// controlSupervisorControls_ButtonRequestCustomerSurvey_Clicked
        private void controlSupervisorControls_ButtonRequestCustomerSurvey_Clicked(object sender, EFS.RC.CommunicatorContext.Operators.CustomerSurvey.RequestCustomerSurveyArgs e)
        {
            try
            {
                // trace
                TRACE_INTERNAL("e.MsgRequest; LyncApplicationId = " + LyncApplicationId);

                // create message
                EFS.RC.CC.Messages.Supervisor.Agent.Request msg = new CC.Messages.Supervisor.Agent.Request();
                msg.RequestText =
                    System.String.Format(EFS.RC.CommunicatorContext.Common.Config.Main.RequestConversationHandoverForSurveyMessage,
                        EFS.RC.CommunicatorContext.Common.Functions.GetCurrentPresenceName(LyncConversation));

                // send event
                SentMessageToContext(msg, OnSendContextDataMessageCompleted);
            }
            catch (System.Exception ex)
            {
                // trace
                TRACE_INTERNAL(ex);

                // show error
                System.Windows.MessageBox.Show("Unexpected Error.", "Error", System.Windows.MessageBoxButton.OK);
            }
        }
        #endregion

        #region PageEvents
        /// Main_Unloaded
        private void Main_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            //StopLyncConnectionUpdate();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
        }

        private void Main_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
        }
        #endregion
    }

}